package com.module.admin.sys.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.module.admin.sys.pojo.SysUser;
import com.system.cache.redis.BaseCache;
import com.system.comm.utils.FrameMd5Util;

/**
 * 用户的token工具类
 * @author yuejing
 * @date 2019年1月12日 下午12:08:55
 * @version V1.0.0
 */
public class SysUserTokenUtil extends BaseCache {

	private static final Logger LOGGER = LoggerFactory.getLogger(SysUserTokenUtil.class);
	private static final String EXP_STRING = "mttoken";
	/** 12小时 */
	private static final int TOKEN_TIMEOUT = 60 * 60 * 12;
	/** 记住密码30天 */
	public static final int TOKEN_TIMEOUT_REMEMBER = 60 * 60 * 24 * 30;

	private static SysUserTokenUtil userTokenUtil;

	private SysUserTokenUtil() {
	}
	public static synchronized SysUserTokenUtil getInstance() {
		if (userTokenUtil == null) {
			userTokenUtil = new SysUserTokenUtil();
		}
		return userTokenUtil;
	}
	
	private String getTokenKey(String token) {
		return "token_" + token;
	}
	private String getSutokenKey(Integer userId) {
		return "sutoken_" + userId;
	}
	
	/**
	 * 创建token
	 * @param user
	 * @return
	 */
	public String createToken(SysUser user) {
		String string = user.getUserId().toString() + System.currentTimeMillis();
		String token = FrameMd5Util.getInstance().encodePassword(string, EXP_STRING);
		String key = getTokenKey(token);
		int timeout = TOKEN_TIMEOUT;
		/*if (user.getRemember() != null && user.getRemember().intValue() == Boolean.TRUE.getCode()) {
			timeout = TOKEN_TIMEOUT_REMEMBER;
		}*/
		user.setToken(token);
		super.set(key, user, timeout);
		
		super.set(getSutokenKey(user.getUserId()), token, timeout);
		return token;
	}

	/**
	 * 根据用户编号获取token信息
	 * @param userId
	 * @return
	 */
	public String getToken(Integer userId) {
		String key = getSutokenKey(userId);
		return super.get(key);
	}
	
	/**
	 * 根据token获取对象
	 * @param token
	 * @return
	 */
	public SysUser getSysUser(String token) {
		String key = getTokenKey(token);
		SysUser user = null;
		try {
			user = super.get(key);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		if (user != null) {
			int timeout = TOKEN_TIMEOUT;
			/*if (member.getRemember() != null && member.getRemember().intValue() == Boolean.TRUE.getCode()) {
				timeout = TOKEN_TIMEOUT_REMEMBER;
			}*/
			super.set(key, user, timeout);
			super.set(getSutokenKey(user.getUserId()), token, timeout);
		}
		return user;
	}
	
	/**
	 * 清除token
	 * @param token
	 */
	public void deleteToken(String token) {
		String key = getTokenKey(token);
		super.delete(key);
	}
	/**
	 * 根据token刷新用户信息
	 * @param token
	 * @param userInfo
	 */
	public void refreshUserInfoByToken(String token, SysUser user) {
		SysUser org = getSysUser(token);
		if (org == null) {
			return;
		}
		int timeout = TOKEN_TIMEOUT;
		user.setToken(token);
		String key = getTokenKey(token);
		super.set(key, user, timeout);
		super.set(getSutokenKey(user.getUserId()), token, timeout);
	}
}